package web.demo.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import web.demo.dao.IFoodTypeDao;
import web.demo.entity.FoodTable;
import web.demo.entity.FoodType;
import web.demo.utils.JdbcUtils;

public class FoodTypeDao extends BaseDao implements IFoodTypeDao{
	/**
	 * 添加菜系
	 * */
	@Override
	public boolean addFoodType(FoodType foodType) {
		String sql="insert into foodType(name) values(?)";
		try {
			int result=JdbcUtils.getQueryRunner().update(sql,foodType.getName());
			if(result>0){
				return true;
			}else{
				return false;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	/**
	 * 查询所有菜品信息
	 * */
	@Override
	public List<FoodType> getAll() {
		String sql="select * from foodType";
		try {
			List<FoodType> list=JdbcUtils.getQueryRunner().query(sql,new BeanListHandler<FoodType>(FoodType.class));
			return list;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	/**
	 * 更新菜系
	 * */
	@Override
	public void update(FoodType foodType) {
		String sql="update foodType set name=? where id=?";
		try{
			int result=JdbcUtils.getQueryRunner().update(sql,foodType.getName(),foodType.getId());
			
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}
	@Override
	public boolean delete(int id) {
		String sql="delete from foodType where id=?";
		try{
			conn=JdbcUtils.getConnection();
			conn.setAutoCommit(false);
			int r1=update(conn,sql,id);
			conn.commit();
			if(r1>0){
				return true;
			}else{
				return false;
			}
		}catch(Exception e){
			try {
				conn.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			throw new RuntimeException(e);
		}finally{
			JdbcUtils.closeAll(conn);
		}
	}
	/**
	 * 根据id查询单个菜品
	 * */
	@Override
	public FoodType getById(int id) {
		String sql="select * from foodType where id=?";
		try{
			return JdbcUtils.getQueryRunner().query(sql,new BeanHandler<FoodType>(FoodType.class),id);
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}
	@Override
	public List<FoodType> select(String str) {
		String sql=null;
		Object condition=null;
		if(str.matches("[0-9]+")){
			//输入的是数字，按照id查询
			condition=Integer.parseInt(str);
			sql="select * from foodType where id=?";
		}
		if(str.matches("[\u4e00-\u9fa5a-zA-Z]+|\\s*")){
			//输入的是中文，按照名称查询
			condition=str.toString();
			condition="%"+condition+"%";
			sql="select * from foodType where name like ?";
		}
		try{
			return JdbcUtils.getQueryRunner().query(sql,new BeanListHandler<FoodType>(FoodType.class),condition);
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}

}
